import Vue from 'vue'
import Vuex from 'vuex'
import router from "../router";
import jwt from 'jsonwebtoken'


import {login} from "@/network/system/user";

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        //赋值
        token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
        username: '',
        id: 0,
        roles: ''
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
            //   这段代码token.token , 是因为在login.vue中调用这个放法传进来的是一个对象
            // （即使你觉的你传进来的是一个字符串，不知道为什么会被放到object里去），
            //   传进来的对象里有token这个属性
            localStorage.setItem("token", token);

        },
        delToken(state) {
            state.token = '';
            localStorage.removeItem("token");
        }
    },
    actions: {
        loginFun(context, payload) {
            login(payload.username, payload.password).then((res) => {
                context.commit('setToken', res.headers.token)
                router.replace('/welcome')

            })
        }
    },
    getters: {
        username: (state) => {
            let tokenInfo = jwt.decode(state.token)
            return state.username = tokenInfo.username
        },
        id: (state) => {
            let tokenInfo = jwt.decode(state.token)
            return state.id = tokenInfo.id
        },
        roles: (state) => {
            let tokenInfo = jwt.decode(state.token)
            return state.roles = tokenInfo.roles
        },
    },
    modules: {}

})
